package com.xxx.blog.service.impl;


import com.github.pagehelper.PageHelper;
import com.xxx.blog.domain.ArticleType;
import com.xxx.blog.mapper.ArticleTypeMapper;
import com.xxx.blog.query.ArticleTypeQuery;
import com.xxx.blog.service.IArticleTypeService;
import com.xxx.blog.dto.ArticleTypeDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class ArticleTypeServiceImpl implements IArticleTypeService {
    @Autowired
    private ArticleTypeMapper articleTypeMapper;
    @Override
    public List<ArticleType> findAll() {
        List<ArticleType> list = articleTypeMapper.findAll();
        return list;
    }

    @Override
    public ArticleType findOne(Long id) {
        return articleTypeMapper.findOne(id);
    }

    @Override
    public List<ArticleType> findByPage(ArticleTypeQuery articleTypeQuery) {
        PageHelper.startPage(articleTypeQuery.getCurrentPage(),articleTypeQuery.getPageSize());
        return articleTypeMapper.findByPage(articleTypeQuery);
    }

    @Override
    public void updateById(ArticleType articleType) {
        articleType.setUpdateTime(new Date());
        articleTypeMapper.updateById(articleType);
    }

    @Override
    public void insert(ArticleType articleType) {
        try {
            articleTypeMapper.insert(articleType);
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }

    @Override
    public void deleteById(Long id) {
        articleTypeMapper.deleteById(id);
    }

    @Override
    public void bathArticleTypes(Long[] ids) {
        articleTypeMapper.bathArticleTypes(ids);
    }

    @Override
    public List<ArticleType> getTypeTree(Long id) {
        ArrayList<ArticleType> typeTree = new ArrayList<>();

        List<ArticleType> all = articleTypeMapper.findAll();
        HashMap<Long, ArticleType> map = new HashMap<>();
        for (ArticleType articleType : all) {
            map.put(articleType.getId(),articleType);
        }

        for (ArticleType articleType : all) {
            //id为包装类,不能够直接==比较
            if (id.equals(articleType.getId())){
                continue;
            }
            if (articleType.getParentId() == null) {
                typeTree.add(articleType);
            }else {
                ArticleType parent = map.get(articleType.getParentId());
                if (parent != null) {
                    parent.getChildren().add(articleType);
                }
            }
        }

        return typeTree;
    }

    @Override
    public List<ArticleTypeDTO> getArticleTypeSta() {
        return articleTypeMapper.getArticleTypeSta();
    }
}
